<template>
  <div class="version-planning-page">
    <header class="page-header">
      <div class="page-title">
        <h2>版本规划</h2>
        <p>从左侧拖拽需求到目标版本，实现需求规划与分配</p>
      </div>
      <div class="page-actions">
        <el-button @click="goBack">
          返回版本管理
        </el-button>
      </div>
    </header>

    <div class="planning-body">
      <section class="backlog-panel" v-loading="backlogLoading">
        <header class="panel-header">
          <div class="panel-title">
            <span>待规划需求</span>
            <el-tag v-if="backlogTotal" size="small" type="info">
              {{ backlogTotal }}
            </el-tag>
          </div>
          <div class="panel-filters">
            <el-input
              v-model="backlogSearch"
              placeholder="搜索需求标题/负责人"
              :prefix-icon="Search"
              clearable
              size="small"
              @clear="loadBacklog"
              @keyup.enter="loadBacklog"
            />
            <el-select
              v-model="backlogFilters.projectId"
              placeholder="项目筛选"
              clearable
              filterable
              size="small"
              style="width: 160px"
              @change="loadBacklog"
            >
              <el-option
                v-for="project in projectOptions"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              />
            </el-select>
            <el-select
              v-model="backlogFilters.priority"
              placeholder="优先级"
              clearable
              size="small"
              style="width: 120px"
              @change="loadBacklog"
            >
              <el-option
                v-for="item in priorityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </header>
        <el-scrollbar class="panel-content">
          <Draggable
            v-model="backlogRequirements"
            item-key="id"
            class="requirement-list"
            group="version-planning"
            :sort="false"
            ghost-class="drag-ghost"
            drag-class="dragging"
            data-version-id="backlog"
            @add="handleBacklogAdd"
          >
            <template #item="{ element }">
              <el-card
                shadow="hover"
                class="requirement-card"
                :data-requirement-id="element.id"
              >
                <div class="requirement-header">
                  <span class="requirement-title" :title="element.title">{{ element.title }}</span>
                  <el-tag
                    v-if="element.priority"
                    :type="getPriorityTagType(element.priority)"
                    size="small"
                  >
                    {{ getPriorityLabel(element.priority) }}
                  </el-tag>
                </div>
                <div class="requirement-meta">
                  <span class="meta-text status-indicator">
                    <span
                      class="status-dot"
                      :style="{ backgroundColor: getRequirementStateColor(element.status) }"
                    />
                    {{ getRequirementStateName(element.status) }}
                  </span>
                  <span class="meta-text">
                    负责人：{{ element.assigneeName || '未分配' }}
                  </span>
                </div>
                <div class="requirement-footer">
                  <span v-if="element.projectName" class="meta-text">
                    {{ element.projectName }}
                  </span>
                  <span v-if="element.dueDate" class="meta-text">
                    截止：{{ formatDate(element.dueDate as string | number | Date, 'YYYY-MM-DD') }}
                  </span>
                </div>
              </el-card>
            </template>
            <template #footer>
              <el-empty
                v-if="backlogRequirements.length === 0 && !backlogLoading"
                description="暂无待规划需求，尝试调整筛选条件"
                :image-size="120"
              />
            </template>
          </Draggable>
        </el-scrollbar>
      </section>

      <section class="versions-panel" v-loading="versionsLoading">
        <header class="panel-header">
          <div class="panel-header-row">
            <div class="panel-title">
              <span>版本排期</span>
              <el-tag v-if="versions.length" size="small" type="info">
                {{ versions.length }}
              </el-tag>
            </div>
            <div class="panel-actions">
              <el-button type="primary" size="small" @click="createDialogVisible = true">
                新建版本
              </el-button>
            </div>
          </div>
          <div class="panel-filters">
            <el-select
              v-model="versionFilters.projectId"
              placeholder="项目筛选"
              clearable
              filterable
              size="small"
              style="width: 160px"
              @change="filterVersions"
            >
              <el-option
                v-for="project in projectOptions"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              />
            </el-select>
            <el-select
              v-model="versionFilters.versionIds"
              placeholder="选择版本"
              multiple
              collapse-tags
              collapse-tags-tooltip
              clearable
              filterable
              size="small"
              style="width: 220px"
              @change="filterVersions"
            >
              <el-option
                v-for="version in versionOptions"
                :key="version.value"
                :label="version.label"
                :value="version.value"
              />
            </el-select>
            <el-input
              v-model="versionFilters.keyword"
              placeholder="搜索版本"
              :prefix-icon="Search"
              clearable
              size="small"
              @clear="filterVersions"
              @keyup.enter="filterVersions"
            />
          </div>
        </header>
        <el-scrollbar class="panel-content versions-scroll">
          <div class="versions-columns">
            <el-collapse v-model="expandedVersions" class="version-collapse">
              <el-collapse-item
                v-for="version in filteredVersions"
                :key="version.id"
                :name="version.id"
              >
                <template #title>
                  <div class="version-collapse-header">
                    <div class="version-header-main">
                      <div class="version-title-block">
                        <span class="version-cycle">{{ version.name }}</span>
                        <span class="version-count"> · {{ (versionRequirementMap[version.id] || []).length }}</span>
                      </div>
                      <VersionStatusTag :status="version.status" size="small" />
                    </div>
                    <div class="version-header-meta">
                      <span class="version-date-range">
                        {{ formatVersionRange(version.start_date, version.planned_release_date) }}
                      </span>
                      <el-tag size="small" effect="plain">{{ version.version_number }}</el-tag>
                    </div>
                  </div>
                </template>

                <el-card class="version-card" shadow="always">
                  <div class="version-card-body">
                    <div class="version-dropzone">
                      <Draggable
                        v-model="versionRequirementMap[version.id]"
                        :key="`${version.id}-draggable`"
                        item-key="id"
                        class="version-requirements"
                        group="version-planning"
                        ghost-class="drag-ghost"
                        drag-class="dragging"
                        :sort="false"
                        :data-version-id="version.id"
                        @add="handleVersionAdd(version.id, $event)"
                      >
                        <template #item="{ element }">
                          <el-card
                            shadow="hover"
                            class="requirement-card"
                            :data-requirement-id="element.id"
                          >
                            <div class="requirement-header">
                              <span class="requirement-title" :title="element.title">
                                {{ element.title }}
                              </span>
                              <el-tag
                                v-if="element.priority"
                                :type="getPriorityTagType(element.priority)"
                                size="small"
                              >
                                {{ getPriorityLabel(element.priority) }}
                              </el-tag>
                            </div>
                            <div class="requirement-meta">
                              <span class="meta-text status-indicator">
                                <span
                                  class="status-dot"
                                  :style="{ backgroundColor: getRequirementStateColor(element.status) }"
                                />
                                {{ getRequirementStateName(element.status) }}
                              </span>
                              <span class="meta-text">
                                负责人：{{ element.assigneeName || '未分配' }}
                              </span>
                              <span v-if="element.projectName" class="meta-text">
                                项目：{{ element.projectName }}
                              </span>
                            </div>
                            <div class="requirement-footer">
                              <span v-if="element.dueDate" class="meta-text">
                                截止：{{ formatDate(element.dueDate as string | number | Date, 'YYYY-MM-DD') }}
                              </span>
                            </div>
                          </el-card>
                        </template>
                        <template #footer>
                          <div
                            v-if="!versionRequirementMap[version.id]?.length && !isVersionRequirementLoading(version.id)"
                            class="version-placeholder"
                          >
                            <el-empty
                              description="拖拽左侧需求到此排期"
                              :image-size="120"
                            />
                            <el-button
                              type="primary"
                              link
                              @click.stop="createRequirement(version)"
                            >
                              新建需求
                            </el-button>
                          </div>
                        </template>
                      </Draggable>
                      <div
                        v-if="isVersionRequirementLoading(version.id)"
                        class="version-loading-mask"
                      >
                        <el-icon><Loading /></el-icon>
                        <span>加载需求中...</span>
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-collapse-item>
            </el-collapse>
            <el-empty
              v-if="!filteredVersions.length && !versionsLoading"
              description="暂无可用版本，尝试新建一个版本计划"
              :image-size="140"
            />
          </div>
        </el-scrollbar>
      </section>
    </div>

    <VersionCreateDialog
      v-model="createDialogVisible"
      @created="handleVersionCreated"
    />
    <RequirementDetail
      v-model:visible="createRequirementDialogVisible"
      :requirement="null"
      :projects="projectOptions"
      :users="requirementUsers"
      :status-options="requirementStatusOptions"
      :priority-options="requirementPriorityOptions"
      :common-tags="requirementCommonTags"
      :current-user-id="currentUserId"
      :default-project-id="requirementDialogTargetVersion?.project_id || ''"
      :default-version-ids="requirementDialogTargetVersion ? [requirementDialogTargetVersion.id] : []"
      @created="handleRequirementDialogCreated"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import Draggable from 'vuedraggable'
import { ElMessage } from 'element-plus'
import { Loading, Search } from '@element-plus/icons-vue'
import VersionStatusTag from '@/components/version/VersionStatusTag.vue'
import VersionCreateDialog from '@/components/version/VersionCreateDialog.vue'
import RequirementDetail from '@/views/requirements/components/RequirementDetail.vue'
import {
  RelationType,
  type Version,
  type VersionWithStats,
  type VersionWorkItemNode,
  versionAPI
} from '@/api/version'
import { getRequirements, type RequirementQueryParams, type RequirementResponse } from '@/api/requirements'
import { projectAPI } from '@/api/project'
import { getUsers } from '@/api/users'
import { ResponseParser } from '@/utils/responseParser'
import { extractVersionItems } from '@/utils/version'
import { formatDate } from '@/utils/date'
import { useRequirementStates } from '@/composables/useRequirementStates'
import { useUserStore } from '@/stores/user'

interface RequirementPlanningItem {
  id: string
  title: string
  status?: string
  priority?: string
  projectId?: string
  projectName?: string
  assigneeId?: string
  assigneeName?: string
  dueDate?: string
  tags?: string[]
}

interface RequirementStatusOption {
  value: string
  label: string
  color?: string
}

interface RequirementPriorityOption {
  value: string
  label: string
}

interface RequirementUserOption {
  id: string
  name: string
}

const router = useRouter()
const {
  getStateName: getRequirementStateName,
  getStateColor: getRequirementStateColor,
  loadStates: loadRequirementStates,
  statusOptions: requirementStatusOptionsComputed
} = useRequirementStates()
const userStore = useUserStore()
const currentUserId = computed(() => userStore.userInfo?.id || '')

const backlogRequirements = ref<RequirementPlanningItem[]>([])
const backlogSearch = ref('')
const backlogLoading = ref(false)
const backlogTotal = ref(0)

const createRequirementDialogVisible = ref(false)
const requirementDialogTargetVersion = ref<VersionWithStats | null>(null)
const requirementUsers = ref<RequirementUserOption[]>([])
const requirementUsersLoaded = ref(false)
const requirementCommonTags = ref<string[]>([])

const backlogFilters = reactive({
  projectId: '',
  priority: ''
})

const priorityOptions = [
  { value: 'urgent', label: '紧急' },
  { value: 'critical', label: '严重' },
  { value: 'high', label: '高' },
  { value: 'medium', label: '中' },
  { value: 'low', label: '低' }
]

const requirementStatusOptions = computed<RequirementStatusOption[]>(() => requirementStatusOptionsComputed.value)
const requirementPriorityOptions = computed<RequirementPriorityOption[]>(() => priorityOptions)

const versions = ref<VersionWithStats[]>([])
const versionsLoading = ref(false)
const versionRequirementMap = reactive<Record<string, RequirementPlanningItem[]>>({})
const versionRequirementLoading = reactive<Record<string, boolean>>({})
const expandedVersions = ref<string[]>([])

const versionFilters = reactive<{
  projectId: string
  keyword: string
  versionIds: string[]
}>({
  projectId: '',
  keyword: '',
  versionIds: []
})

const versionOptions = computed(() =>
  versions.value.map(version => ({
    label: `${version.name} (${version.version_number})`,
    value: version.id
  }))
)

const filteredVersions = computed(() => {
  const keyword = versionFilters.keyword.trim().toLowerCase()
  return versions.value.filter(version => {
    const matchProject =
      !versionFilters.projectId || version.project_id === versionFilters.projectId
    const matchSelection =
      !versionFilters.versionIds.length || versionFilters.versionIds.includes(version.id)
    const matchKeyword =
      !keyword ||
      version.name.toLowerCase().includes(keyword) ||
      version.version_number.toLowerCase().includes(keyword)
    return matchProject && matchSelection && matchKeyword
  })
})

const createDialogVisible = ref(false)
const projectOptions = ref<{ id: string; name: string }[]>([])

const getPriorityTagType = (priority?: string): 'danger' | 'warning' | 'success' | 'info' => {
  const map: Record<string, 'danger' | 'warning' | 'success' | 'info'> = {
    urgent: 'danger',
    critical: 'danger',
    high: 'warning',
    medium: 'info',
    low: 'success'
  }
  return map[priority || ''] || 'info'
}

const getPriorityLabel = (priority?: string) => {
  const labelMap: Record<string, string> = {
    urgent: '紧急',
    critical: '严重',
    high: '高',
    medium: '中',
    low: '低'
  }
  return labelMap[priority || ''] || '未设置'
}

const isVersionRequirementLoading = (versionId: string) => {
  return !!versionRequirementLoading[versionId]
}

const goBack = () => {
  router.push({ name: 'Versions' })
}

const formatVersionRange = (start?: string | null, end?: string | null) => {
  const startText = start ? formatDate(start, 'YYYY.MM.DD') : '未开始'
  const endText = end ? formatDate(end, 'YYYY.MM.DD') : '未设置'
  return `${startText} - ${endText}`
}

const createRequirement = async (version: VersionWithStats) => {
  requirementDialogTargetVersion.value = version
  await loadRequirementUsers()
  createRequirementDialogVisible.value = true
}

const loadProjects = async () => {
  try {
    const response = await projectAPI.getProjects({ page: 1, size: 100 })
    const parsed = ResponseParser.parseListResponse(response)
    projectOptions.value = Array.isArray(parsed.items)
      ? parsed.items
          .filter((project: any) => project && project.id && project.name)
          .map((project: any) => ({
            id: project.id,
            name: project.name
          }))
      : []
  } catch (error) {
    console.error('加载项目列表失败', error)
    const message = ResponseParser.extractMessage(error) || '加载项目列表失败'
    ElMessage.error(message)
    projectOptions.value = []
  }
}

const mapRequirementFromResponse = (item: any): RequirementPlanningItem => {
  return {
    id: item.id,
    title: item.title || '未命名需求',
    status: item.status || '',
    priority: item.priority || '',
    projectId: item.project_id || '',
    projectName: item.project_name || '',
    assigneeId: item.assignee_id || '',
    assigneeName: item.assignee_name || item.assignee?.name || item.owner_name || '',
    dueDate: item.due_date || '',
    tags: Array.isArray(item.tags) ? item.tags : []
  }
}

const mapRequirementFromVersion = (item: VersionWorkItemNode): RequirementPlanningItem => {
  const meta = item.meta || {}
  return {
    id: item.requirement_id || item.id,
    title:
      item.title ||
      meta.requirement_title ||
      meta.title ||
      '未命名需求',
    status: item.status || meta.requirement_status || '',
    priority: item.priority || meta.priority || '',
    projectId: meta.project_id || '',
    projectName: meta.project_name || '',
    assigneeId: item.assignee_id || meta.assignee_id || '',
    assigneeName: item.assignee_name || meta.assignee_name || '',
    dueDate: item.due_date || meta.due_date || '',
    tags: Array.isArray(meta.tags) ? meta.tags : []
  }
}

const loadBacklog = async () => {
  backlogLoading.value = true
  try {
    const params: RequirementQueryParams = {
      page: 1,
      size: 100,
      has_version: false
    }
    if (backlogFilters.projectId) {
      params.project_id = backlogFilters.projectId
    }
    if (backlogFilters.priority) {
      params.priority = backlogFilters.priority as any
    }
    if (backlogSearch.value.trim()) {
      params.search = backlogSearch.value.trim()
    }

    const response = await getRequirements(params)
    const parsed = ResponseParser.parseRequirementListResponse(response)
    backlogRequirements.value = parsed.items.map(mapRequirementFromResponse)
    backlogTotal.value = parsed.total
  } catch (error) {
    console.error('获取待规划需求失败', error)
    backlogRequirements.value = []
    backlogTotal.value = 0
    const message = ResponseParser.extractMessage(error) || '获取需求列表失败'
    ElMessage.error(message)
  } finally {
    backlogLoading.value = false
  }
}

const loadRequirementUsers = async () => {
  if (requirementUsersLoaded.value) {
    return
  }
  try {
    const response = await getUsers({ page: 1, size: 200 })
    const parsed = ResponseParser.parseListResponse(response)
    requirementUsers.value = Array.isArray(parsed.items)
      ? parsed.items
          .filter((user: any) => user && user.id)
          .map((user: any) => ({
            id: user.id,
            name: user.name || user.nickname || user.full_name || user.username || '未命名用户'
          }))
      : []
    requirementUsersLoaded.value = true
  } catch (error) {
    console.error('加载用户列表失败', error)
    requirementUsers.value = []
    requirementUsersLoaded.value = false
  }
}

const ensureVersionEntry = (versionId: string) => {
  if (!versionRequirementMap[versionId]) {
    versionRequirementMap[versionId] = []
  }
}

const loadVersionRequirements = async (versionId: string) => {
  ensureVersionEntry(versionId)
  versionRequirementLoading[versionId] = true
  try {
    const response = await versionAPI.getVersionWorkItems(versionId)
    if (response.success && response.data) {
      const items = response.data.items || {}
      const requirements = Array.isArray(items.requirements) ? items.requirements : []
      versionRequirementMap[versionId] = requirements
        .filter(item => (item.type || 'requirement') === 'requirement')
        .map(mapRequirementFromVersion)
    } else {
      versionRequirementMap[versionId] = []
    }
  } catch (error) {
    console.error(`加载版本 ${versionId} 需求失败`, error)
    versionRequirementMap[versionId] = []
  } finally {
    versionRequirementLoading[versionId] = false
  }
}

const loadVersions = async () => {
  versionsLoading.value = true
  try {
    const response = await versionAPI.getVersions({ page: 1, size: 30, sort_by: 'planned_release_date' })
    const versionList = extractVersionItems(response)
    versionList.forEach(version => ensureVersionEntry(version.id))
    versions.value = versionList
    expandedVersions.value = versionList.map(version => version.id)
    await Promise.all(versionList.map(version => loadVersionRequirements(version.id)))
  } catch (error) {
    console.error('获取版本列表失败', error)
    versions.value = []
    const message = ResponseParser.extractMessage(error) || '获取版本列表失败'
    ElMessage.error(message)
  } finally {
    versionsLoading.value = false
  }
}

const filterVersions = () => {
  // computed 属性会自动更新，无需额外逻辑
}

interface DragEventWithItem extends DragEvent {
  item?: HTMLElement
  from?: HTMLElement
}

const handleBacklogAdd = async (evt: DragEventWithItem) => {
  const requirementId = evt?.item?.dataset?.requirementId
  const fromVersionId = evt?.from?.dataset?.versionId
  if (!requirementId || !fromVersionId || fromVersionId === 'backlog') {
    return
  }
  try {
    await versionAPI.removeRequirementFromVersion(fromVersionId, requirementId)
    ElMessage.success('需求已移出版本')
    await loadBacklog()
    await loadVersionRequirements(fromVersionId)
  } catch (error) {
    console.error('移除需求失败', error)
    const message = ResponseParser.extractMessage(error) || '移除需求失败'
    ElMessage.error(message)
    await loadVersionRequirements(fromVersionId)
    await loadBacklog()
  }
}

const handleVersionAdd = async (versionId: string, evt: DragEventWithItem) => {
  const requirementId = evt?.item?.dataset?.requirementId
  const fromContainer = evt?.from?.dataset?.versionId || 'backlog'
  if (!requirementId) {
    return
  }

  try {
    if (fromContainer && fromContainer !== 'backlog' && fromContainer !== versionId) {
      await versionAPI.removeRequirementFromVersion(fromContainer, requirementId)
    }

    await versionAPI.addRequirementToVersion(versionId, {
      requirement_id: requirementId,
      relation_type: RelationType.INCLUDED
    })

    if (fromContainer === 'backlog') {
      backlogRequirements.value = backlogRequirements.value.filter(item => item.id !== requirementId)
      backlogTotal.value = Math.max(backlogTotal.value - 1, 0)
    }

    ElMessage.success('需求已添加到版本')
    await loadVersionRequirements(versionId)
  } catch (error) {
    console.error('关联需求失败', error)
    const message = ResponseParser.extractMessage(error) || '关联需求失败'
    ElMessage.error(message)
    await loadVersionRequirements(versionId)
    if (fromContainer && fromContainer !== 'backlog') {
      await loadVersionRequirements(fromContainer)
    } else {
      await loadBacklog()
    }
  }
}

const handleVersionCreated = async (_version: Version) => {
  createDialogVisible.value = false
  await loadVersions()
  await loadBacklog()
}

const handleRequirementDialogCreated = async (requirement: RequirementResponse) => {
  const targetVersion = requirementDialogTargetVersion.value
  createRequirementDialogVisible.value = false
  if (!requirement || !requirement.id || !targetVersion) {
    requirementDialogTargetVersion.value = null
    return
  }
  try {
    await versionAPI.addRequirementToVersion(targetVersion.id, {
      requirement_id: requirement.id,
      relation_type: RelationType.INCLUDED
    })
    ElMessage.success('需求已创建并关联到版本')
    await loadVersionRequirements(targetVersion.id)
    await loadBacklog()
  } catch (error) {
    console.error('关联新建需求到版本失败', error)
    const message = ResponseParser.extractMessage(error) || '关联新建需求失败'
    ElMessage.error(message)
  } finally {
    requirementDialogTargetVersion.value = null
  }
}

watch(
  () => backlogSearch.value,
  value => {
    if (!value) {
      loadBacklog()
    }
  }
)

watch(
  () => filteredVersions.value.map(version => version.id),
  ids => {
    const visibleSet = new Set(ids)
    const current = expandedVersions.value.filter(id => visibleSet.has(id))
    if (current.length === 0) {
      expandedVersions.value = ids.length ? [ids[0]] : []
    } else {
      expandedVersions.value = current
    }
  },
  { immediate: true }
)

watch(
  () => versionFilters.versionIds.slice(),
  selected => {
    if (selected.length) {
      const allowed = filteredVersions.value
        .map(version => version.id)
        .filter(id => selected.includes(id))
      expandedVersions.value = allowed.length ? allowed : expandedVersions.value
    } else if (!expandedVersions.value.length) {
      expandedVersions.value = filteredVersions.value.map(version => version.id)
    }
  }
)

watch(
  createRequirementDialogVisible,
  value => {
    if (!value) {
      requirementDialogTargetVersion.value = null
    }
  }
)

watch(
  versions,
  newVersions => {
    if (!Array.isArray(newVersions)) {
      versionFilters.versionIds = []
      return
    }
    const validIds = versionFilters.versionIds.filter(id =>
      newVersions.some(version => version.id === id)
    )
    if (validIds.length !== versionFilters.versionIds.length) {
      versionFilters.versionIds = validIds
      filterVersions()
    }
  }
)

const initializePlanning = async () => {
  await loadRequirementStates()
  await Promise.all([loadProjects(), loadBacklog(), loadVersions(), loadRequirementUsers()])
}

initializePlanning()
</script>

<style scoped>
.version-planning-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
  padding: 16px;
  background-color: #f5f7fa;
  box-sizing: border-box;
  overflow: hidden;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  flex-shrink: 0;
  flex-wrap: wrap;
  gap: 12px;
}

.page-title {
  flex: 1;
  min-width: 0;
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  color: #1f2d3d;
  font-weight: 600;
}

.page-title p {
  margin: 4px 0 0;
  color: #909399;
  font-size: 13px;
}

.page-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.planning-body {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 16px;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.backlog-panel,
.versions-panel {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(31, 45, 61, 0.05);
  min-height: 0;
  overflow: hidden;
}

.panel-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 12px;
}

.panel-header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.panel-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
  color: #1f2d3d;
}

.panel-filters {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.panel-content {
  flex: 1;
  min-height: 0;
}

.versions-scroll {
  padding-right: 4px;
}

.requirement-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-height: 100%;
}

.requirement-card {
  cursor: grab;
  transition: transform 0.15s ease, box-shadow 0.15s ease;
}

.requirement-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 18px rgba(64, 158, 255, 0.15);
}

.requirement-card:active {
  cursor: grabbing;
}

.requirement-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
}

.requirement-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.requirement-title {
  flex: 1;
  font-size: 14px;
  font-weight: 600;
  color: #1f2d3d;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.requirement-meta,
.requirement-footer {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 12px;
  color: #606266;
  flex-wrap: wrap;
}

.meta-text {
  color: #606266;
}

.status-indicator {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  color: #606266;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #909399;
}

.versions-columns {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-bottom: 8px;
}

.version-collapse {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.version-collapse-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
}

.version-header-main {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.version-title-block {
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
}

.version-cycle {
  color: #1f2d3d;
}

.version-count {
  color: #909399;
  font-size: 14px;
}

.version-header-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 13px;
  color: #606266;
}

.version-date-range {
  color: #606266;
}

.version-dropzone {
  position: relative;
  flex: 1;
  min-height: 160px;
  padding: 12px;
  border-radius: 12px;
  background-color: #f8fafc;
  border: 1px solid #e4e7ed;
  margin-top: 8px;
}

.version-card {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.version-card-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.version-requirements {
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-height: 140px;
}

.version-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 24px 0;
  color: #909399;
}

.version-collapse :deep(.el-collapse-item__header) {
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 12px;
  margin-bottom: 8px;
}

.version-collapse :deep(.el-collapse-item__wrap) {
  border: none;
}

.version-collapse :deep(.el-collapse-item__content) {
  padding: 0 0 12px;
}

.drag-ghost {
  opacity: 0.6;
  border: 1px dashed #409eff;
}

.dragging {
  cursor: grabbing;
}

.version-loading-mask {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.85);
  border-radius: 10px;
  color: #409eff;
  font-size: 13px;
}

@media (max-width: 1440px) {
  .version-planning-page {
    padding: 12px;
    gap: 12px;
  }
  
  .planning-body {
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
  }
  
  .backlog-panel,
  .versions-panel {
    padding: 12px;
  }
}

@media (max-width: 1200px) {
  .version-planning-page {
    padding: 12px;
    gap: 12px;
  }
  
  .planning-body {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .backlog-panel,
  .versions-panel {
    min-height: 400px;
  }
}

@media (max-width: 768px) {
  .version-planning-page {
    padding: 8px;
    gap: 8px;
  }
  
  .page-header {
    padding: 12px 16px;
    flex-direction: column;
    align-items: stretch;
  }
  
  .page-title h2 {
    font-size: 18px;
  }
  
  .page-title p {
    font-size: 12px;
  }
  
  .page-actions {
    width: 100%;
  }
  
  .page-actions .el-button {
    width: 100%;
  }
  
  .planning-body {
    gap: 8px;
  }
  
  .backlog-panel,
  .versions-panel {
    padding: 12px;
    border-radius: 6px;
    min-height: 350px;
  }
  
  .panel-header {
    gap: 8px;
    margin-bottom: 8px;
  }
  
  .panel-title {
    font-size: 14px;
  }
  
  .panel-filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .panel-filters .el-input,
  .panel-filters .el-select {
    width: 100%;
  }
  
  .requirement-card {
    margin-bottom: 8px;
  }
  
  .requirement-card :deep(.el-card__body) {
    padding: 10px;
    gap: 6px;
  }
  
  .requirement-title {
    font-size: 13px;
  }
  
  .requirement-meta,
  .requirement-footer {
    font-size: 11px;
    gap: 8px;
  }
}
</style>

